class Student < ApplicationRecord
  has_many :appointment_records
  belongs_to :potential_student
  has_many :student_remarks
  belongs_to :studio
  belongs_to :market_employee, class_name: "Employee", foreign_key: "market_employee_id",optional: true
  belongs_to :service_employee, class_name: "Employee", foreign_key: "service_employee_id",optional: true
  belongs_to :student_group_configuration, foreign_key: "student_group"
  belongs_to :company
  has_many :student_cards
  has_many :check_ins
  has_many :student_orders, class_name: "Order", foreign_key: "student_id"
  has_many :course_reckons


  def shopping_level 
    if self.accumulated_amount.blank? 
      '-'
    else
      if self.accumulated_amount < 5000
        "小于5K"
      elsif self.accumulated_amount >= 5000 && self.accumulated_amount < 10000
        "5K-10K"
      elsif self.accumulated_amount >= 10000 && accumulated_amount < 20000
        "10K-20K"
      elsif self.accumulated_amount >= 20000
        "20K以上"
      end
    end
  end

  def cards_category
    cards = self.student_cards
    p cards.size
    if cards.blank?
      return '-'
    elsif cards.size > 1
      return "#{cards.first.card_type} 等"
    elsif cards.size == 1
     return cards.first.card_type
    end
  end

  def student_age_group
    if self.birthday.blank?
      '-'
    else
      if (self.birthday < (Date.current - 3.year)) && (self.birthday > (Date.current - 6.year))
        '幼儿'
      elsif (self.birthday < (Date.current - 6.year)) && (self.birthday > (Date.current - 12.year))
        "少年"
      elsif (self.birthday < (Date.current - 12.year)) && (self.birthday > (Date.current - 18.year))
        "青少年"
      elsif (self.birthday < (Date.current - 18.year))
        "成年"
      else
        "-"
      end
    end
  end

  def is_expire  
    year_card = true 
    self.student_cards.where("invalidated_at > :invalidated_at and card_type = :card_type", invalidated_at: Time.now, card_type: "年卡" ).each do |card|
      if card.invalidated_at > (Time.now + 1.month)
        year_card = false 
      end
    end
    month_card = true
    self.student_cards.where("invalidated_at > :invalidated_at and card_type = :card_type", invalidated_at: Time.now, card_type: "月卡" ).each do |card|
      if card.invalidated_at > (Time.now + 1.month)
        month_card = false
      end
    end
    times_card = true
    self.student_cards.where("invalidated_at > :invalidated_at and card_type = :card_type", invalidated_at: Time.now, card_type: "次卡" ).each do |card|
      if card.amount > 5
        times_card = false
      end
    end
    top_up_card = true
    self.student_cards.where("invalidated_at > :invalidated_at and card_type = :card_type", invalidated_at: Time.now, card_type: "月卡" ).each do |card|
      if card.amount > 100
        top_up_card = false
      end
    end
    year_card && month_card && times_card && top_up_card
  end


end
